import pandas as pd
import numpy as np
from faker import Faker
import random
from datetime import datetime, timedelta

# 初始化Faker和随机种子
fake = Faker('zh_CN')
np.random.seed(42)
random.seed(42)


# 生成模拟数据函数
def generate_life_insurance_data(num_policies=1000):
    data = []
    products =  ["终身寿险", "年金保险", "重大疾病险", "两全保险", "分红保险"]
    channels =  ["代理人", "银行保险", "线上直销", "经纪公司", "电话销售"]
    statuses =  ["有效", "失效", "满期", "理赔中", "已赔付"]

    for _ in range(num_policies):
        # 基础信息
        policy_no = f"POL{random.randint(1000000, 9999999)}"
        issue_date = fake.date_between(start_date='-10y', end_date='-1y')
        product = random.choice(products)
        channel = random.choice(channels)
        premium = round(random.uniform(5000, 50000), 2)
        sum_insured = round(premium * random.uniform(10, 50), 2)
        term = random.choice([10, 15, 20, 25, 30])

        # 客户信息
        client_name = fake.name()
        client_age = random.randint(25, 65)
        client_gender = random.choice(["M", "F"])

        # 状态和日期
        status = random.choice(statuses)
        if status in ["满期", "失效"]:
            lapse_date = fake.date_between(start_date=issue_date, end_date='now')
        else:
            lapse_date = None

        # 理赔信息
        claim_amount = 0
        if status in ["已赔付", "理赔中"]:
            claim_amount = round(sum_insured * random.uniform(0.3, 1.0), 2)

        # 成本计算
        acquisition_cost = round(premium * random.uniform(0.05, 0.15), 2)
        maintenance_cost = round(premium * random.uniform(0.02, 0.08), 2)

        # 利润计算
        years_in_force = (datetime.now().year - issue_date.year)
        total_premium = premium * min(years_in_force, term)
        profit = total_premium - claim_amount - acquisition_cost - (maintenance_cost * years_in_force)

        data.append({
            "工单ID": "LIFE-PROF-20250730-001",
            "保单号": policy_no,
            "产品类型": product,
            "销售渠道": channel,
            "签发日期": issue_date,
            "投保人": client_name,
            "年龄": client_age,
            "性别": client_gender,
            "年缴保费": premium,
            "累计保费": total_premium,
            "保额": sum_insured,
            "保险期限": term,
            "保单状态": status,
            "理赔金额": claim_amount,
            "获客成本": acquisition_cost,
            "维护成本": maintenance_cost,
            "预期利润": profit,
            "销售区域": fake.province()
        })

    return pd.DataFrame(data)


# 生成盈利能力分析报告
def generate_profitability_report(df):
    report = {
        "总体指标": {
            "总保费收入": df["累计保费"].sum(),
            "总赔付金额": df["理赔金额"].sum(),
            "总运营成本": df["获客成本"].sum() + df["维护成本"].sum() * df["保险期限"].mean(),
            "净利润率": (df["预期利润"].sum() / df["累计保费"].sum()) * 100
        },
        "产品线分析": df.groupby("产品类型").agg({
            "累计保费": "sum",
            "预期利润": "sum",
            "保单号": "count"
        }).rename(columns={"保单号": "保单数量"}),
        "渠道分析": df.groupby("销售渠道").agg({
            "累计保费": "sum",
            "获客成本": "mean",
            "预期利润": "sum"
        }),
        "风险分析": {
            "赔付率": (df["理赔金额"].sum() / df["累计保费"].sum()) * 100,
            "高风险产品": df.groupby("产品类型")["理赔金额"].sum().idxmax(),
            "高风险区域": df.groupby("销售区域")["理赔金额"].sum().idxmax()
        }
    }
    return report


# 生成数据和分析报告
if __name__ == "__main__":
    # 生成模拟数据
    insurance_df = generate_life_insurance_data(1000)

    # 保存到CSV
    insurance_df.to_csv("人寿保险盈利能力数据.csv", index=False, encoding='utf-8-sig')

    # 生成分析报告
    report = generate_profitability_report(insurance_df)

    # 打印报告摘要
    print("人寿保险盈利能力分析报告")
    print("=" * 50)
    print(f"分析周期: 2024Q3 - 2025Q2")
    print(f"总保单数: {len(insurance_df)}")
    print(f"总保费收入: ¥{report['总体指标']['总保费收入']:,.2f}")
    print(f"净利润率: {report['总体指标']['净利润率']:.2f}%")
    print("\n产品线盈利能力排名:")
    print(report['产品线分析'].sort_values("预期利润", ascending=False))

    # 可视化建议
    print("\n建议可视化图表:")
    print("1. 各产品线保费收入与利润对比柱状图")
    print("2. 销售渠道成本效益气泡图")
    print("3. 区域赔付率热力图")
    print("4. 客户年龄与保费关系散点图")



